package hc

import (
	"math/rand"
	"reflect"
	"time"
)

/**
一些助手函数
*/

// Struct2Map 结构体转map
func Struct2Map(obj interface{}) map[string]interface{} {
	t := reflect.TypeOf(obj)
	v := reflect.ValueOf(obj)

	var data = make(map[string]interface{})
	for i := 0; i < t.NumField(); i++ {
		// data[t.Field(i).Name] = v.Field(i).Interface()
		key := t.Field(i).Tag.Get("param")
		if key != "" {
			data[key] = v.Field(i).Interface()
		}
	}
	return data
}

// GetOffset 根据当前页和每页数量, 获取sql查询的偏移量
func GetOffset(page, pageSize int) int {
	if page <= 1 {
		return 0
	}
	return (page - 1) * pageSize
}

// GetZRange 根据当前页和每页数量, 获取sql查询的偏移量
func GetZRange(page, pageSize int) (start, end int) {
	if page <= 1 {
		return 0, pageSize - 1
	}
	return (page - 1) * pageSize, page*pageSize - 1
}

// RandomString 生成随机字符串
func RandomString(length int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyz"
	bytes := []byte(str)
	result := make([]byte, length)
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < length; i++ {
		result[i] = bytes[r.Intn(len(str))]
	}
	return string(result)
}
